import { AnnounceManageAPI } from '../common/type';
import pageStyles from '@/common/pageLayout.less';
import { Button, Card, Col, Divider, message, Row, Space, Tooltip } from 'antd';
import { useCallback, useContext, useMemo, useState } from 'react';
import { AnnounceDetailContext } from '../common/UpdateContext';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import {
  downloadTemplate,
  getColorTextLoadMap,
  getCompanyID,
  getPosIDs,
  getTenantID,
  getUserDepID,
  getUserID,
  splitFileUrl,
} from '@/utils';
import MyIcon from '@/components/MyIcon';
import cls from 'classnames';
import { AnnounceCheckModal } from './AnnounceCheckModal';
import { AnnounceCancelModal } from './AnnounceCancelModal';
import { editAnnounceService } from '../service';
import { VerticalRightOutlined } from '@ant-design/icons';

export const DetailLeftView: React.FC<AnnounceManageAPI.IDetailLeftView> = () => {
  const { prefixCls, announceInfo, curRes, reloadAnnounceInfo } = useContext(
    AnnounceDetailContext,
  );

  /**
   * 处理文件显示
   */
  const fileList = useMemo(() => {
    let attachList: any[] = [];
    attachList = splitFileUrl(announceInfo?.attachUrl);
    return attachList;
  }, [announceInfo]);

  /**
   * 返回文件名称处理
   * @param fileName 文件对象
   * @returns
   */
  const getFileNameNotType = (fileName: any) => {
    let arr: string[] = fileName?.split('.');
    let endType: any = arr?.pop();
    let nameStr: string = arr.join('');
    if (nameStr.length >= 6) {
      nameStr = nameStr.substr(0, 3) + '...' + nameStr.substr(-1);
    }
    return nameStr + `.${endType}`;
  };

  /**
   * 处理是否展示操作按钮框
   */
  const handleOperation = useMemo(() => {
    let isShowBtn: any = {
      allBtnDiv: false,
      applyBtn: false,
      cancelBtn: false,
      issuedBtn: false,
    };
    if (
      curRes?.['/announceController/addCheck'] &&
      announceInfo?.createrID == getUserID() &&
      (announceInfo?.state == `${getTenantID()}12021000` ||
        announceInfo?.state == `${getTenantID()}12021003`)
    ) {
      isShowBtn['applyBtn'] = true;
      isShowBtn['allBtnDiv'] = true;
    }
    if (
      curRes?.['/announceController/cancel'] &&
      (announceInfo?.state == `${getTenantID()}12021000` ||
        announceInfo?.state == `${getTenantID()}12021003` ||
        announceInfo?.state == `${getTenantID()}12021005`)
    ) {
      isShowBtn['cancelBtn'] = true;
      isShowBtn['allBtnDiv'] = true;
    }

    if (
      curRes?.['/announceController/sign'] &&
      (announceInfo?.state == `${getTenantID()}12021000` ||
        announceInfo?.state == `${getTenantID()}12021003`)
    ) {
      isShowBtn['issuedBtn'] = true;
      isShowBtn['allBtnDiv'] = true;
    }

    return isShowBtn;
  }, [curRes, announceInfo]);

  /**
   * 审核modal
   */
  const [checkModal, setCheckModal] = useState<boolean>(false);

  /**
   * 作废modal
   */
  const [cancelModal, setCancelModal] = useState<boolean>(false);

  /**
   * isSued
   */
  const isSuedCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadAnnounceInfo();
    } else {
      message.error(res?.msg);
    }
  };

  const { editAnnounceRun } = editAnnounceService(isSuedCallback);

  /**
   * 保存监听的滚动条高度
   */
  const [scrollHeight, setScrollHeight] = useState<number>(0);
  const scrollHeightCallback = useCallback(
    (height: number) => {
      setScrollHeight(height);
    },
    [scrollHeight],
  );

  /**
   * 回到顶部
   */
  const backToTopFunc = (nodeId: string) => {
    let anchorElement = document.getElementById(nodeId);
    if (anchorElement) {
      anchorElement?.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
  };

  /**
   * 监听鼠标是否移入移出
   * true 移入    false 移出
   */
  const [hoverBackTop, setHoverBackTop] = useState<boolean>(false);

  /**
   * 监听 公告内容滚动
   * @param event
   */
  const monitorScrolling = (event: any) => {
    let { target } = event;
    if (target.scrollTop > document.body?.clientHeight * 0.3) {
      scrollHeightCallback(target?.scrollTop);
    }

    if (target?.scrollTop < document.body?.clientHeight * 0.3) {
      if (scrollHeight != 0) {
        scrollHeightCallback(0);
        setHoverBackTop(false);
      }
    }
  };

  return (
    <div
      className={prefixCls + 'row-col-divBox'}
      style={{
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <Card
        title={'公告详情'}
        className={cls(
          pageStyles['page-view'],
          prefixCls + 'cardExtra',
          prefixCls + 'cardHead',
        )}
        bodyStyle={{ height: '90%', padding: '5px 0px' }}
        extra={
          announceInfo?.isTop == 1 ? (
            <div className={prefixCls + 'cardExtra-iconIsTop'}>
              <MyIcon type="icon-zhiding" />
            </div>
          ) : (
            <></>
          )
        }
      >
        <Row className={'cardBodyRow'}>
          <Col span={24} className={'cardBodyCol'}>
            <div className={prefixCls + 'announceDetail'}>
              <Row
                style={{
                  padding: '0px 10px',
                  marginRight: 0,
                  marginLeft: 0,
                }}
                gutter={[10, 10]}
              >
                <Col span={20}>
                  <div className={prefixCls + 'announceDetail-title'}>
                    {announceInfo?.announceTypeName && (
                      <>
                        【
                        {
                          getColorTextLoadMap(announceInfo?.announceTypeName)
                            ?.colorText
                        }
                        】
                      </>
                    )}
                    {announceInfo?.announceTitle}
                  </div>
                  <div
                    className={prefixCls + 'announceDetail-content'}
                    style={{ fontSize: '14px' }}
                  >
                    公示时间：
                    <span style={{ color: '#545454' }}>
                      {announceInfo?.startTime?.split(' ')?.[0] ?? '--'}
                      &nbsp;~&nbsp;
                      {announceInfo?.endTime?.split(' ')?.[0] ?? '--'}
                    </span>
                  </div>
                </Col>
                <Col
                  span={4}
                  className={prefixCls + 'announceDetail-titleRightCol'}
                >
                  <div
                    style={{
                      padding: '5px 10px',
                      border: '1px solid #e4e4e4',
                    }}
                  >
                    <MyIcon type="icon-dian" />
                    &nbsp;
                    <span
                      style={{
                        color: getColorTextLoadMap(announceInfo?.stateName)
                          ?.color,
                      }}
                    >
                      {getColorTextLoadMap(announceInfo?.stateName)?.colorText}
                    </span>
                  </div>
                </Col>
              </Row>
              <Divider />
              <div
                style={{ height: document.body.clientHeight * 0.3 }}
                className={prefixCls + 'announceDetail-scrollBox'}
              >
                <ScrollBarLayout
                  style={{
                    padding: '5px 20px',
                  }}
                  onScroll={monitorScrolling}
                >
                  <Row id={'announceViewScroll'}>
                    <Col span={24}>
                      <div
                        style={{ fontSize: '20px' }}
                        dangerouslySetInnerHTML={{
                          __html: announceInfo?.announceContent
                            ? announceInfo?.announceContent?.contentHtml
                            : '',
                        }}
                        className={pageStyles['editorStyle']}
                      />
                      <div className={prefixCls + 'announceDetail-contentUser'}>
                        <div>
                          {announceInfo?.state == `${getTenantID()}12021002` ? (
                            <>
                              <div>
                                发布人：
                                <span style={{ color: '#545454' }}>
                                  {(announceInfo && announceInfo?.signerName) ||
                                    '--'}
                                </span>
                              </div>
                              <div>
                                发布部门：
                                <span style={{ color: '#545454' }}>
                                  {(announceInfo &&
                                    announceInfo?.signDepartmentName) ||
                                    '--'}
                                </span>
                              </div>
                              <div>
                                发布时间：
                                <span style={{ color: '#545454' }}>
                                  {(announceInfo && announceInfo?.signTime) ||
                                    '--'}
                                </span>
                              </div>
                            </>
                          ) : (
                            <>
                              <div>
                                编制人：
                                <span style={{ color: '#545454' }}>
                                  {(announceInfo &&
                                    announceInfo?.createrName) ||
                                    '--'}
                                </span>
                              </div>
                              <div>
                                编制部门：
                                <span style={{ color: '#545454' }}>
                                  {(announceInfo &&
                                    announceInfo?.createDepartmentName) ||
                                    '--'}
                                </span>
                              </div>
                              <div>
                                编制时间：
                                <span style={{ color: '#545454' }}>
                                  {(announceInfo && announceInfo?.createTime) ||
                                    '--'}
                                </span>
                              </div>
                            </>
                          )}
                        </div>
                      </div>
                    </Col>
                  </Row>
                </ScrollBarLayout>
              </div>
            </div>
            {((fileList && fileList.length > 0) ||
              handleOperation?.allBtnDiv) && (
              <div className={prefixCls + 'announceBottom'}>
                {fileList && fileList.length > 0 && (
                  <div className={prefixCls + 'fileListBox'}>
                    <div className={prefixCls + 'fileListBox-labelText'}>
                      附件列表：
                    </div>
                    <Row
                      className={prefixCls + 'fileListBox-row'}
                      gutter={[10, 6]}
                    >
                      <>
                        {fileList.map((e: any, i: any) => {
                          return (
                            <Col span={6} key={i}>
                              <Tooltip title={e.attachName}>
                                <a
                                  onClick={() => {
                                    message.success('下载中，请稍后...');
                                    downloadTemplate(
                                      '/announceController/downloadFile',
                                      e.attachName,
                                      e.attachUrl,
                                      () => {},
                                    );
                                  }}
                                >
                                  <MyIcon type="icon-file-text-fill" />
                                  &nbsp;
                                  {getFileNameNotType(e.attachName)}
                                </a>
                              </Tooltip>
                            </Col>
                          );
                        })}
                      </>
                    </Row>
                  </div>
                )}
                {handleOperation?.allBtnDiv && (
                  <div
                    className={'cardBodybtn'}
                    style={{
                      border: 0,
                      paddingBottom: 0,
                    }}
                  >
                    <Space>
                      {handleOperation?.issuedBtn && (
                        <Button
                          type={'primary'}
                          onClick={() => {
                            let payload: any = {
                              id: announceInfo?.id,
                              versionNum: announceInfo?.versionNum,
                              announceTitle: announceInfo?.announceTitle,
                              announceContent: announceInfo?.announceContent,
                              announceType: announceInfo?.announceType,
                              viewRange: announceInfo?.viewRange,
                              attachUrl: announceInfo?.attachUrl,
                              state: announceInfo?.state,
                              isTop: announceInfo?.isTop,
                              startTime: announceInfo?.startTime,
                              endTime: announceInfo?.endTime,
                              receiveDeptIds: announceInfo?.receiveDeptIds,

                              signType: 0,
                              signerID: getUserID(),
                              signPositionID: getPosIDs(),
                              signDepartmentID: getUserDepID(),
                              signCompanyID: getCompanyID(),
                            };
                            editAnnounceRun(payload);
                          }}
                        >
                          直接签发
                        </Button>
                      )}
                      {handleOperation?.applyBtn && (
                        <Button
                          type={'primary'}
                          onClick={() => {
                            setCheckModal(true);
                          }}
                        >
                          提交审核
                        </Button>
                      )}
                      {handleOperation?.cancelBtn && (
                        <Button
                          type={'primary'}
                          onClick={() => {
                            setCancelModal(true);
                          }}
                        >
                          作废
                        </Button>
                      )}
                    </Space>
                  </div>
                )}
              </div>
            )}
          </Col>
        </Row>
      </Card>

      {scrollHeight > document.body.clientHeight * 0.3 && (
        <>
          <div
            onMouseEnter={(e: any) => {
              e?.stopPropagation();
              setHoverBackTop(true);
            }}
            onMouseLeave={(e: any) => {
              e?.stopPropagation();
              setHoverBackTop(false);
            }}
            className={prefixCls + 'backTopStyle'}
            onClick={() => {
              backToTopFunc('announceViewScroll');
            }}
          >
            <div className={prefixCls + 'backTopStyle-circleDiv'}>
              {hoverBackTop ? (
                <>
                  <div>返回</div>
                  <div>顶部</div>
                </>
              ) : (
                <>
                  <VerticalRightOutlined />
                </>
              )}
            </div>
          </div>
        </>
      )}

      {/* 发起审核 */}
      {checkModal && (
        <AnnounceCheckModal
          onClose={() => {
            setCheckModal(false);
          }}
          isShowModal={checkModal}
          checkRows={announceInfo}
          reloadAnnounce={() => {
            reloadAnnounceInfo();
          }}
        />
      )}

      {/* 作废 */}
      {cancelModal && (
        <AnnounceCancelModal
          onClose={() => {
            setCancelModal(false);
          }}
          isShowModal={cancelModal}
          checkRows={announceInfo}
          reloadAnnounce={() => {
            reloadAnnounceInfo();
          }}
        />
      )}
    </div>
  );
};
